package com.example.bluetoothclicker.bluetoothreceiver

import android.bluetooth.BluetoothDevice
import android.content.BroadcastReceiver
import android.content.Context
import android.content.Intent

object BluetoothReceiver : BroadcastReceiver() {

    private val observers = mutableListOf<BluetoothObserver>()

    // 注册观察者
    fun registerObserver(observer: BluetoothObserver) {
        if (!observers.contains(observer)) {
            observers.add(observer)
        }
    }

    // 注销观察者
    fun unregisterObserver(observer: BluetoothObserver) {
        observers.remove(observer)
    }

    override fun onReceive(context: Context?, intent: Intent?) {
        if (intent == null) return

        when (intent.action) {
            // 发现蓝牙设备
            BluetoothDevice.ACTION_FOUND -> {
                val device: BluetoothDevice? = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE)
                device?.let {
                    notifyDeviceDiscovered(it)
                }
            }

            // 蓝牙设备配对状态改变
            BluetoothDevice.ACTION_BOND_STATE_CHANGED -> {
                val device: BluetoothDevice? = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE)
                val bondState = intent.getIntExtra(BluetoothDevice.EXTRA_BOND_STATE, -1)
                if (bondState == BluetoothDevice.BOND_BONDED) {
                    device?.let {
                        notifyPairingCompleted(it)
                    }
                }
            }

            // 蓝牙设备连接
            BluetoothDevice.ACTION_ACL_CONNECTED -> {
                val device: BluetoothDevice? = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE)
                device?.let {
                    notifyConnectionStateChanged(it, true)
                }
            }

            // 蓝牙设备断开连接
            BluetoothDevice.ACTION_ACL_DISCONNECTED -> {
                val device: BluetoothDevice? = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE)
                device?.let {
                    notifyConnectionStateChanged(it, false)
                }
            }
        }
    }

    // 通知所有观察者：发现设备
    private fun notifyDeviceDiscovered(device: BluetoothDevice) {
        observers.forEach { it.onDeviceDiscovered(device) }
    }

    // 通知所有观察者：配对完成
    private fun notifyPairingCompleted(device: BluetoothDevice) {
        observers.forEach { it.onPairingCompleted(device) }
    }

    // 通知所有观察者：连接状态变化
    private fun notifyConnectionStateChanged(device: BluetoothDevice, isConnected: Boolean) {
        observers.forEach { it.onConnectionStateChanged(device, isConnected) }
    }
}
